package huffman;
import java.util.LinkedList;



public class BitBuffer extends LinkedList<Boolean> {
	private static final long serialVersionUID = 36435943710363004L;
	private final int maxsize;
	public BitBuffer(int size) {
		maxsize = size;
//		super(size);
	}
	
	/*
	 * http://www.bytemycode.com/snippets/snippet/811/
	 */
	public static boolean[] convertToBits(byte b) {
        boolean[] bits = new boolean[8];
        for (int i = 0; i < bits.length; i++) {
            bits[7 - i] = ((b & (1 << i)) != 0);
        }
        return bits;
    }
	
	public static boolean[] convertToBits(int b) {
        boolean[] bits = new boolean[32];
        for (int i = 0; i < bits.length; i++) {
            bits[31 - i] = ((b & (1 << i)) != 0);
        }
        return bits;
    }
	
	public static boolean[] convertToShort(short b) {
        boolean[] bits = new boolean[16];
        for (int i = 0; i < bits.length; i++) {
            bits[15 - i] = ((b & (1 << i)) != 0);
        }
        return bits;
    }
	
	public Byte toByteShift() {
		while(this.size() < 8) {
			addFirst(false);
		}
			String s = "";
			Object a[] = super.toArray();
			for(int i = 0; i < 8; i++) {
				Boolean b = (Boolean) a[i];
				if(b == Boolean.TRUE) {
					s+= "1";
				} else {
					s+= "0";
				}
			}
			
			return Integer.valueOf(s, 2).byteValue();
	}
	
	public Byte toByte() {
		while(this.size() < 8) {
			add(false);
		}
			String s = "";
			Object a[] = super.toArray();
			for(int i = 0; i < 8; i++) {
				Boolean b = (Boolean) a[i];
				if(b == Boolean.TRUE) {
					s+= "1";
				} else {
					s+= "0";
				}
			}
			
			return Integer.valueOf(s, 2).byteValue();
	}
	public void add(Byte v) {
		boolean bar[] = BitBuffer.convertToBits(v);
		for(boolean b: bar)  {
			this.add(b);
		}
	}
	public Integer toInteger() {
		while(this.size() < 32) {
			add(false);
		}
			String s = "";
			Object a[] = super.toArray();
			for(int i = 0; i < 32; i++) {
				Boolean b = (Boolean) a[i];
				if(b == Boolean.TRUE) {
					s+= "1";
				} else {
					s+= "0";
				}
			}
			return Integer.parseInt(s, 2);
	}

	public int remainingCapacity() {
		return maxsize - size();
	}
}
